package thread.aqs;

import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
import java.util.concurrent.locks.LockSupport;

import sun.misc.Unsafe;

/**
 * 闲谈：在这个类中，所有同步的方法，只要被用户中断了，【调用Thread#interrupt】方法，都会抛出
 * 【中断异常】，这是因为：【AQS】是通过【park/unpark】机制，来实现线程之间的同步通信的。
 * 但是【park/unpark】无法阻塞被中断的线程。所以它需要提醒调用者，【某个线程不能被park暂停，因为它出现了【中断】】。
 */

/**
 * 提供了一个框架，用来实现【依赖于先进先出（FIFO）的等待队列】的【阻塞锁和相关的同步器（semaphores、events等）】，
 * 这个类是为了解决【状态为单个原子{@code int}的值】提供的一个基础类。如果希望操作【{@code long}类型】，需要使用 {@link AbstractQueuedLongSynchronizer}类。
 * 【它的子类必须实现此类的受保护的方法】。【并定义该状态在获取或释放此对象方面的含义】。并且只有在使用
 * 【{@link #getState}、{@link #setState}、{@link #compareAndSetState}操作的原子更新的int值才会被跟踪同步。】。
 * 需要实现的方法，一共就四个，是{@code protected}修饰的，且没有{@code final}的方法。
 *
 * <p> 子类应定义为【非公共内部辅助类{@code non-public}】，
 * 用于实现其封闭类的同步属性。
 * {@code AbstractQueuedSynchronizer}不实现任何同步接口。
 * 相反，它定义了诸如【可获取中断{@link #acquireInterruptibly}】之类的方法，
 * 【具体锁和相关同步器】可以在适当的时候调用这些方法来实现它们的公共方法。
 *
 * <p>此类支持【独占模式】和【共享模式】中的【一种或两种】。
 * 在【独占模式】下获取时，【其他线程尝试获取的操作无法成功】。
 * 多线程获取【共享模式】【可能会（但不一定）成功（共享模式，读读不阻塞，但是写与其他操作阻塞）】。
 * 这个类不“理解”这些差异，除非在机械意义上，当【共享模式】获取成功时，下一个【等待线程（如果存在）也必须确定它是否也可以获取】。
 * 在【不同模式下等待的线程共享相同的FIFO队列】。
 * 通常，【实现子类只支持其中一种模式】，但两者都可以发挥作用，例如在{@link ReadWriteLock}中。
 * 仅支持【独占或共享模式】的子类【不需要定义】支持未使用模式的方法。
 * 下面的四个方法，就是独占/共享模式需要实现的方法。
 * <ul>
 * <li> {@link #tryAcquire}
 * <li> {@link #tryRelease}
 * <li> {@link #tryAcquireShared}
 * <li> {@link #tryReleaseShared}
 * </ul>
 *
 * <p>此类定义了一个嵌套的{@link ConditionObject}类，
 * 可以被支持【独占模式的子类】用作{@link Condition}实现，
 * 方法{@link #isHeldExclusive}可以判断是否对当前线程独占同步，
 * 使用{@link #release}方法，会释放锁，{@link #acquire}方法，会获取锁。
 * 没有{@link AbstractQueuedSynchronizer}类中的方法会创建{@link ConditionObject}对象，
 * 因此如果【因此，如果这个条件对象无法满足子类的场景】，请不要使用它。
 * 当然{@link ConditionObject}取决于其子类同步器实现的实现。
 *
 * <p>此类为【内部队列（FIFO队列）】提供【检查】、【检测】和【监视】方法，
 * 并为【条件对象（ConditionObject）】提供类似的方法。这些可以根据需要导出到类中，
 * 使用{@code AbstractQueuedSynchronizer}作为其同步机制。
 *
 * <p>此类的【序列化仅存储维护状态的底层原子整数】，
 * 因此【反序列化的对象】具有【空线程队列】。需要可序列化性的典型子类将定义一个{@code readObject}方法，
 * 该方法在反序列化时将其恢复到已知的初始状态。
 *
 * <h3>使用</h3>
 *
 * <p>如果想要使用这个类，需要根据子类的特性，选择实现下面的几种方法。
 *
 * <ul>
 * <li> {@link #tryAcquire}
 * <li> {@link #tryRelease}
 * <li> {@link #tryAcquireShared}
 * <li> {@link #tryReleaseShared}
 * <li> {@link #isHeldExclusively}
 * </ul>
 *
 * 上面的每一种方法，默认的实现都是抛出 {@link UnsupportedOperationException}。
 * 子类的实现，必须是内部线程安全的，并且实现的过程【应该短，而且不能阻塞】。
 * 其他的所有方法都被 {@code final}修饰，不能重写。
 *
 * <p>您可能还会发现从{@link AbstractOwnableSynchronizer}类中继承的方法，
 * 这些方法对于跟踪拥有【独占同步器的线程】很有用。
 * 我们鼓励您使用它们——这使得监控和诊断工具能够帮助用户确定哪些线程持有锁。
 *
 *
 * <p>即使此类基于内部FIFO队列。
 * 但是它却【不会自动执行】FIFO获取策略。
 * 独占同步的核心形式如下：
 *
 * <pre>
 * Acquire: 获取锁
 *     while (!tryAcquire(arg)) { //尝试获取锁。由子类实现。
 *        <em>如果线程尚未排队，则将其排队。</em>;
 *        <em>可能会阻塞当前线程。</em>;
 *     }
 *
 * Release: 释放锁
 *     if (tryRelease(arg))//尝试释放锁。由子类实现。
 *        <em>唤醒队列中的第一个线程。</em>;
 * </pre>
 *
 * (共享模式类似，但可能涉及级联信号。)
 *
 * <p id="barging">
 *     因为在查询之前会调用获取中的检查，
 *     所以【新的获取线程】【可能】会在【其他被阻塞和排队的线程之前中断】。
 *     但是，如果需要，您可以定义{@link #tryAcquire}、{@link #tryAcquireShared}，
 *     通过内部调用一种或多种检查方法来禁用{@code barging}，从而提供【公平的FIFO采集顺序】。
 *     特别是，大多数公平同步器可以定义{@link #tryAcquire}方法，返回{@code false}，如果{@link #hasQueuedPredecessors}（一种专门为公平同步器设计的方法）返回true。
 *     其他变化也是可能的。
 *
 * <p>Throughput and scalability are generally highest for the
 * default barging (also known as <em>greedy</em>,
 * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
 * While this is not guaranteed to be fair or starvation-free, earlier
 * queued threads are allowed to recontend before later queued
 * threads, and each recontention has an unbiased chance to succeed
 * against incoming threads.  Also, while acquires do not
 * &quot;spin&quot; in the usual sense, they may perform multiple
 * invocations of {@code tryAcquire} interspersed with other
 * computations before blocking.  This gives most of the benefits of
 * spins when exclusive synchronization is only briefly held, without
 * most of the liabilities when it isn't. If so desired, you can
 * augment this by preceding calls to acquire methods with
 * "fast-path" checks, possibly prechecking {@link #hasContended}
 * and/or {@link #hasQueuedThreads} to only do so if the synchronizer
 * is likely not to be contended.
 *
 * <p>This class provides an efficient and scalable basis for
 * synchronization in part by specializing its range of use to
 * synchronizers that can rely on {@code int} state, acquire, and
 * release parameters, and an internal FIFO wait queue. When this does
 * not suffice, you can build synchronizers from a lower level using
 * {@link java.util.concurrent.atomic atomic} classes, your own custom
 * {@link java.util.Queue} classes, and {@link LockSupport} blocking
 * support.
 *
 * <h3>Usage Examples</h3>
 *
 * <p>Here is a non-reentrant mutual exclusion lock class that uses
 * the value zero to represent the unlocked state, and one to
 * represent the locked state. While a non-reentrant lock
 * does not strictly require recording of the current owner
 * thread, this class does so anyway to make usage easier to monitor.
 * It also supports conditions and exposes
 * one of the instrumentation methods:
 *
 *  <pre> {@code
 * class Mutex implements Lock, java.io.Serializable {
 *
 *   // Our internal helper class
 *   private static class Sync extends AbstractQueuedSynchronizer {
 *     // Reports whether in locked state
 *     protected boolean isHeldExclusively() {
 *       return getState() == 1;
 *     }
 *
 *     // Acquires the lock if state is zero
 *     public boolean tryAcquire(int acquires) {
 *       assert acquires == 1; // Otherwise unused
 *       if (compareAndSetState(0, 1)) {
 *         setExclusiveOwnerThread(Thread.currentThread());
 *         return true;
 *       }
 *       return false;
 *     }
 *
 *     // Releases the lock by setting state to zero
 *     protected boolean tryRelease(int releases) {
 *       assert releases == 1; // Otherwise unused
 *       if (getState() == 0) throw new IllegalMonitorStateException();
 *       setExclusiveOwnerThread(null);
 *       setState(0);
 *       return true;
 *     }
 *
 *     // Provides a Condition
 *     Condition newCondition() { return new ConditionObject(); }
 *
 *     // Deserializes properly
 *     private void readObject(ObjectInputStream s)
 *         throws IOException, ClassNotFoundException {
 *       s.defaultReadObject();
 *       setState(0); // reset to unlocked state
 *     }
 *   }
 *
 *   // The sync object does all the hard work. We just forward to it.
 *   private final Sync sync = new Sync();
 *
 *   public void lock()                { sync.acquire(1); }
 *   public boolean tryLock()          { return sync.tryAcquire(1); }
 *   public void unlock()              { sync.release(1); }
 *   public Condition newCondition()   { return sync.newCondition(); }
 *   public boolean isLocked()         { return sync.isHeldExclusively(); }
 *   public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
 *   public void lockInterruptibly() throws InterruptedException {
 *     sync.acquireInterruptibly(1);
 *   }
 *   public boolean tryLock(long timeout, TimeUnit unit)
 *       throws InterruptedException {
 *     return sync.tryAcquireNanos(1, unit.toNanos(timeout));
 *   }
 * }}</pre>
 *
 * <p>Here is a latch class that is like a
 * {@link java.util.concurrent.CountDownLatch CountDownLatch}
 * except that it only requires a single {@code signal} to
 * fire. Because a latch is non-exclusive, it uses the {@code shared}
 * acquire and release methods.
 *
 *  <pre> {@code
 * class BooleanLatch {
 *
 *   private static class Sync extends AbstractQueuedSynchronizer {
 *     boolean isSignalled() { return getState() != 0; }
 *
 *     protected int tryAcquireShared(int ignore) {
 *       return isSignalled() ? 1 : -1;
 *     }
 *
 *     protected boolean tryReleaseShared(int ignore) {
 *       setState(1);
 *       return true;
 *     }
 *   }
 *
 *   private final Sync sync = new Sync();
 *   public boolean isSignalled() { return sync.isSignalled(); }
 *   public void signal()         { sync.releaseShared(1); }
 *   public void await() throws InterruptedException {
 *     sync.acquireSharedInterruptibly(1);
 *   }
 * }}</pre>
 *
 * @since 1.5
 * @author Doug Lea
 */
public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable {

    /**  序列化id */
    private static final long serialVersionUID = 7373984972572414691L;

    /**
     * 空参构造器。
     */
    protected AbstractQueuedSynchronizer() { }

    /**
     * 这个是AQS中的一个内部类。
     * 【阻塞队列的node节点】。
     *
     * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and
     * Hagersten) lock queue. CLH locks are normally used for
     * spinlocks.  We instead use them for blocking synchronizers, but
     * use the same basic tactic of holding some of the control
     * information about a thread in the predecessor of its node.  A
     * "status" field in each node keeps track of whether a thread
     * should block.  A node is signalled when its predecessor
     * releases.  Each node of the queue otherwise serves as a
     * specific-notification-style monitor holding a single waiting
     * thread. The status field does NOT control whether threads are
     * granted locks etc though.  A thread may try to acquire if it is
     * first in the queue. But being first does not guarantee success;
     * it only gives the right to contend.  So the currently released
     * contender thread may need to rewait.
     *
     * <p>下面是CLH队列的图示，它只会从尾部进队列，头部出队列。
     * <pre>
     *      +------+  prev +-----+       +-----+
     * head |      | <---- |     | <---- |     |  tail
     *      +------+       +-----+       +-----+
     * </pre>
     *
     * <p>Insertion into a CLH queue requires only a single atomic
     * operation on "tail", so there is a simple atomic point of
     * demarcation from unqueued to queued. Similarly, dequeuing
     * involves only updating the "head". However, it takes a bit
     * more work for nodes to determine who their successors are,
     * in part to deal with possible cancellation due to timeouts
     * and interrupts.
     *
     * <p>The "prev" links (not used in original CLH locks), are mainly
     * needed to handle cancellation. If a node is cancelled, its
     * successor is (normally) relinked to a non-cancelled
     * predecessor. For explanation of similar mechanics in the case
     * of spin locks, see the papers by Scott and Scherer at
     * http://www.cs.rochester.edu/u/scott/synchronization/
     *
     * <p>We also use "next" links to implement blocking mechanics.
     * The thread id for each node is kept in its own node, so a
     * predecessor signals the next node to wake up by traversing
     * next link to determine which thread it is.  Determination of
     * successor must avoid races with newly queued nodes to set
     * the "next" fields of their predecessors.  This is solved
     * when necessary by checking backwards from the atomically
     * updated "tail" when a node's successor appears to be null.
     * (Or, said differently, the next-links are an optimization
     * so that we don't usually need a backward scan.)
     *
     * <p>Cancellation introduces some conservatism to the basic
     * algorithms.  Since we must poll for cancellation of other
     * nodes, we can miss noticing whether a cancelled node is
     * ahead or behind us. This is dealt with by always unparking
     * successors upon cancellation, allowing them to stabilize on
     * a new predecessor, unless we can identify an uncancelled
     * predecessor who will carry this responsibility.
     *
     * <p>CLH queues need a dummy header node to get started. But
     * we don't create them on construction, because it would be wasted
     * effort if there is never contention. Instead, the node
     * is constructed and head and tail pointers are set upon first
     * contention.
     *
     * <p>Threads waiting on Conditions use the same nodes, but
     * use an additional link. Conditions only need to link nodes
     * in simple (non-concurrent) linked queues because they are
     * only accessed when exclusively held.  Upon await, a node is
     * inserted into a condition queue.  Upon signal, the node is
     * transferred to the main queue.  A special value of status
     * field is used to mark which queue a node is on.
     *
     * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
     * Scherer and Michael Scott, along with members of JSR-166
     * expert group, for helpful ideas, discussions, and critiques
     * on the design of this class.
     */
    static final class Node {
        /** 指明当前锁，是一个共享锁 */
        static final Node SHARED = new Node();
        /** 指明当前锁，是一个排他锁 */
        static final Node EXCLUSIVE = null;

        /** waitStatus 的值，表示线程已取消获取锁资源了。 */
        static final int CANCELLED =  1;
        /** waitStatus 的值，指示【后继线程】需要执行【unpark】方法，取消线程阻塞。 */
        static final int SIGNAL    = -1;
        /** waitStatus 的值，表示【当前线程】被【Condition】阻塞了。 */
        static final int CONDITION = -2;
        /**
         * waitStatus 的值，表示下一次的【acquireShared（获取共享锁）】应无条件传播。
         */
        static final int PROPAGATE = -3;

//        CANCELLED（1）： 因为超时或者中断，节点会被设置为取消状态，被取消的节点时不会参与到竞争中的，他会一直保持取消状态不会转变为其他状态；
//        SIGNAL（-1）：后继节点的线程处于等待状态，而当前节点的线程如果释放了同步状态或者被取消，将会通知后继节点，使后继节点的线程得以运行
//        CONDITION（-2） ： 点在等待队列中，节点线程等待在Condition上，当其他线程对Condition调用了signal后，改节点将会从等待队列中转移到同步队列中，加入到同步状态的获取中
//        PROPAGATE（-3） ： 表示下一次共享式同步状态获取将会无条件地传播下去
//        INIT（ 0）:
        /**
         * 状态字段，取值只有下面的几种：
         * <ul>
         *      <li>1：SIGNAL：这个节点的【后继节点】，被阻塞了，（是通过【park】方法）。所以在【这个节点】将要被【release、cancels】的时候，
         *          需要【unpark 唤醒】它的后继节点。【为了避免竞争】，{@link #acquire}方法必须首先指示它们需要一个信号，然后重试原子获取，然后在失败时阻塞。
         *      <li>2：CANCELLED：这个节点【被取消了】，由于【timeout、interrupt（超时、打断）】，节点不会离开这个状态，
         *          并且，具有取消状态的节点，永远不会被阻塞。
         *      <li>3：CONDITION：这个节点表示，当前线程被【Condition】条件变量，阻塞了。
         *      <li>4：PROPAGATE：这个节点表示，应该让【后继节点】获取锁【releaseShared 方法】。这个设置只对【head】节点生效。
         *      <li>5：【0】：以上都不是。
         *
         * <p> 这些值按数字排列以简化使用。非负值意味着节点不需要发出信号。因此，大多数代码不需要检查特定值，只需要检查符号。
         *
         * <p> 对于一般节点来说，这个字段为0。
         *  简化了一下； > 0 表示线程状态已取消。
         *             = 0 表示节点是一个常规节点。
         *             < 0 表示节点被各种原因阻塞了，需要执行后继的节点。
         */
        volatile int waitStatus;

        /**
         * 当前节点的【前驱节点】。
         * Link to predecessor node that current node/thread relies on
         * for checking waitStatus. Assigned during enqueuing, and nulled
         * out (for sake of GC) only upon dequeuing.  Also, upon
         * cancellation of a predecessor, we short-circuit while
         * finding a non-cancelled one, which will always exist
         * because the head node is never cancelled: A node becomes
         * head only as a result of successful acquire. A
         * cancelled thread never succeeds in acquiring, and a thread only
         * cancels itself, not any other node.
         */
        volatile Node prev;

        /**
         * 当前节点的【后继节点】。
         * Link to the successor node that the current node/thread
         * unparks upon release. Assigned during enqueuing, adjusted
         * when bypassing cancelled predecessors, and nulled out (for
         * sake of GC) when dequeued.  The enq operation does not
         * assign next field of a predecessor until after attachment,
         * so seeing a null next field does not necessarily mean that
         * node is at end of queue. However, if a next field appears
         * to be null, we can scan prev's from the tail to
         * double-check.  The next field of cancelled nodes is set to
         * point to the node itself instead of null, to make life
         * easier for isOnSyncQueue.
         */
        volatile Node next;

        /**
         * 当前节点持有的线程。可能会为空。
         */
        volatile Thread thread;

        /**
         * 分不同的情况：
         *      1：在AQS的同步队列中，用这个属性表示当前锁是【共享锁】或者【排他锁】。
         *      2：在【ConditionObject】中，用这个字段，来维持一个阻塞队列的单向链表。
         */
        Node nextWaiter;

        /**
         * 判断当前锁是不是一个【共享锁】。
         */
        final boolean isShared() {
            return nextWaiter == SHARED;
        }

        /**
         * 获取当前节点的【前驱节点】。可能为空，这个【非空】判断，是为了帮助【VM】虚拟机。
         */
        final Node predecessor() throws NullPointerException {
            Node p = prev;
            //如果当前节点的前驱节点为空，则抛异常。
            if (p == null)
                throw new NullPointerException();
            else
                return p;
        }

        //空参构造器。
        Node() {
        }

        /**
         * 被【addWaiter】方法使用。
         * @param mode：表示当前节点是【共享模式】，还是【独占模式】。
         */
        Node(Thread thread, Node mode) {
            this.nextWaiter = mode;
            this.thread = thread;
        }

        /**
         * 用在【创建Condition对象】中。
         */
        Node(Thread thread, int waitStatus) {
            this.waitStatus = waitStatus;
            this.thread = thread;
        }
    }

    /**
     * 等待队列的头节点，【延迟初始化】。
     * 【除了初始化】，它只能通过方法【setHead】进行修改。
     * 注意：【如果head存在，则其waitStatus保证不会是CANCELLED】。
     */
    private transient volatile Node head;

    /**
     * 延迟初始化，等待队列的【尾节点】，可以通过{@link #enq}方法添加一个尾节点。
     */
    private transient volatile Node tail;

    /**
     * 同步器的状态，就是通过这个值，进行一些【可重入】、【判断读写锁】等操作。
     */
    private volatile int state;

    /**
     * 获取当前的state的值。
     */
    protected final int getState() {
        return state;
    }

    /**
     * 设置state的值。
     */
    protected final void setState(int newState) {
        state = newState;
    }

    /**
     * 原子操作，对【state】变量，进行更新。后续的更新只能通过这个方法，【state】是被{@code volatile}修饰的。
     * CAS操作。
     */
    protected final boolean compareAndSetState(int expect, int update) {
        //对【state】变量进行，CAS操作。
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }

    // 队列的工具

    /**
     * 一个常数，这个常数之内的，JUC会选择【自旋】等待，大于这个时间的【JUC会使用park方法阻塞当前线程】。
     * 相当于是一个考虑，在这个时间之外的，JUC认为，可以执行CPU线程的切换。
     * 这是因为：CPU线程切换，也涉及到，线程上下文的切换，比较花费时间，这个时间【JUC认为是1000ns，比较合理】。
     */
    static final long spinForTimeoutThreshold = 1000L; //单位纳秒，1000ns = 1微秒

    /**
     * 入队列的方法，如果没有【tail、head】节点需要初始化。
     * @param node the node to insert
     * @return 节点的前驱。
     */
    private Node enq(final Node node) {
        for (;;) {
            //拿到【尾节点】。
            Node t = tail;
            //如果为空，必须初始化。
            if (t == null) {
                //设置头节点。
                if (compareAndSetHead(new Node()))
                    //将头节点设置为【尾节点】。
                    tail = head;
            } else {
                //将待插入节点【node】的【前驱节点】，设置为【t（tail节点）】。
                node.prev = t;
                //执行CAS操作，将【等待队列】的【尾节点】，设置为【node】。
                if (compareAndSetTail(t, node)) {
                    //将【原来的t（tail节点）】的【后继节点（CLH队列是一个环，所以这个是head的前驱节点）】。指向node。形成闭环。
                    t.next = node;
                    return t;
                }
            }
        }
    }

    /**
     * 为【当前线程】和【给定的模式，独占/共享】。创建一个入队的节点。
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
     * @return the new node
     */
    private Node addWaiter(Node mode) {
        //创建一个节点。
        Node node = new Node(Thread.currentThread(), mode);
        //第一次入队：这是快速入队的一种方式。为了不进入enq方法，【也就是当竞争少的时候，可以在外面执行一次快速入队】。
        //获取【尾节点】。
        Node pred = tail;
        if (pred != null) {
            //将当前node节点的【前驱节点】执行【pred（tail节点）】/
            node.prev = pred;
            //执行CAS操作，更换【tail尾节点的值为node】。
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        //如果失败了，就需要调用【enq】方法，进行死循环的入队。
        enq(node);
        return node;
    }

    /**
     * 设置节点为队列头节点的方法。只有在{@link #acquire}方法中，会调用。
     * 为了方便GC，它会把一些无用的字段，置为{@code null}，比如。【thread、prev】等信息。
     */
    private void setHead(Node node) {
        head = node;
        node.thread = null;
        node.prev = null;
    }

    /**
     * 唤醒当前节点的后继节点，如果存在的话。
     */
    private void unparkSuccessor(Node node) {
        /*
         * 如果当前节点的waitStatus<0，表示它的状态为【waitStatus = SINGAL】。
         * 这个状态是，需要唤醒【这个节点】的一个【后继节点】。所以为了【避免重入唤醒】。
         * 需要将这个状态重置为【waitStatus = 0】，表示以后，后继节点，不由我唤醒了。
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * 去【unpark】一个后继节点，这一步是找到一个后继节点，这个节点的【!waitStatus > 0 】，也就是说这个【waitStatus != CANCELLED】.
         */
        Node s = node.next;
        //如果后继节点的状态是，CANCELLED。
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                //找到一个【后继节点】，不为CANCELLED的节点。
                if (t.waitStatus <= 0)
                    s = t;
        }
        //如果找到了这个【后继节点】。
        if (s != null)
            LockSupport.unpark(s.thread);//执行unpark方法，唤醒被park的后继节点。
    }

    /**
     * Release action for shared mode -- signals successor and ensures
     * propagation. (Note: For exclusive mode, release just amounts
     * to calling unparkSuccessor of head if it needs signal.)
     * 释放一个共享模式的锁 -- 它会是下一次获取共享锁，无条件的传播下去。【即 PROPAGATE 状态】。
     * 如果释放的是独占模式的锁{@link #release}，-- 它会调用 {@link #unparkSuccessor} 方法，唤醒下一个节点（如果有必要的话）。
     * 一句话：释放一个共享锁的操作是：将【阻塞队列】中的【所有】的节点，都置为【PROPAGATE】。
     *      以便下次获取共享锁时，可以【正常传播（就是让后续节点，可以继续获取锁）】。
     *      分为几种情况：因为【waitStatus】有几种状态。
     *          1：【SIGNAL】：这个状态表示，后继线程被【park】阻塞了，所有，这个节点首先需要将，【后继节点唤醒（unpark方法）】，
     *                  再变成【PROPAGATE】状态，为了下次获取共享锁做准备。
     *          2：【CONDITION】：这个状态表示。当前节点被【条件变量】阻塞了，在【共享模式】中不可能出现。
     *          3：【PROPAGATE】：这个状态不用改变。
     *          4：【CANCELLED】：不会改动这个状态。
     *          5：【0】：表示是一个正常的节点，可以最直接转换状态。
     * 
     */
    private void doReleaseShared() {
        /*
         * 确保release的【propagates】，即使还有其他正在进行的【获取/发布】。
         * 这是按照通常的方式进行的，即如果需要【SIGNAL】，它会尝试取消【unparkSuccessor】后继的节点。
         * 但如果没有，状态将设置为【PROPAGATE】，
         * 以确保在【release】时继续【propagates】。
         * 此外，【我们必须循环】，【以防在执行此操作时添加新节点】。
         * 此外，与【unparkSuccessor】的其他使用不同，我们需要知道【CAS重置状态是否失败】，
         * 如果是，则重新检查。
         */
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);   //如果是【SIGNAL】，就需要唤醒一个后继节点。
                }
                else if (ws == 0 &&
                        !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

    /**
     * Sets head of queue, and checks if successor may be waiting
     * in shared mode, if so propagating if either propagate > 0 or
     * PROPAGATE status was set.
     * 设置队列的头，并检查【它的后继节点】是不是一个【共享模式】。
     * 如果是，就需要唤醒后续的所有节点【直到遇到了一个非共享模式的节点为止】。
     *
     * @param node the node
     * @param propagate the return value from a tryAcquireShared
     */
    private void setHeadAndPropagate(Node node, int propagate) {
        Node h = head; // 之前的头节点。
        setHead(node); //将该node节点，设置为头节点。
        /*
         * 尝试去唤醒下一个节点。如果：
         *
         * Try to signal next queued node if:
         *   Propagation was indicated by caller,
         *     or was recorded (as h.waitStatus either before
         *     or after setHead) by a previous operation
         *     (note: this uses sign-check of waitStatus because
         *      PROPAGATE status may transition to SIGNAL.)
         * and
         *   The next node is waiting in shared mode,
         *     or we don't know, because it appears null
         *
         * The conservatism in both of these checks may cause
         * unnecessary wake-ups, but only when there are multiple
         * racing acquires/releases, so most need signals now or soon
         * anyway.
         */
        if (propagate > 0 || h == null || h.waitStatus < 0 ||
                (h = head) == null || h.waitStatus < 0) {
            //拿到当前节点的后继节点。如果当前节点是一个【独占节点】，或者后继节点是一个【共享节点】。就调用【doReleaseShared】方法。
            //它会持续唤醒：该节点到后面遇到的第一个【独占模式】的节点中间的所有节点。
            Node s = node.next;
            if (s == null || s.isShared())
                doReleaseShared();
        }
    }

    // 各种版本的acquire的实用程序

    /**
     * 取消一个正在获取锁的节点。
     */
    private void cancelAcquire(Node node) {
        // 如果节点为空，则忽视这个节点。
        if (node == null)
            return;
        //将该节点的线程设置为null。
        node.thread = null;

        // 跳过状态为：取消的【前驱节点们】。
        //如果【pred】节点为，取消状态的节点，那么这一步就会将这个节点的连接断开。
        Node pred = node.prev;
        while (pred.waitStatus > 0)
            node.prev = pred = pred.prev;

        // predNext is the apparent node to unsplice. CASes below will
        // fail if not, in which case, we lost race vs another cancel
        // or signal, so no further action is necessary.
        Node predNext = pred.next;

        // Can use unconditional write instead of CAS here.
        // After this atomic step, other Nodes can skip past us.
        // Before, we are free of interference from other threads.
        //将当前节点的状态，修改为：取消【CANCELLED】。
        node.waitStatus = Node.CANCELLED;

        // If we are the tail, remove ourselves.
        if (node == tail && compareAndSetTail(node, pred)) {
            compareAndSetNext(pred, predNext, null);
        } else {
            // If successor needs signal, try to set pred's next-link
            // so it will get one. Otherwise wake it up to propagate.
            int ws;
            if (pred != head &&
                    ((ws = pred.waitStatus) == Node.SIGNAL ||
                            (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
                    pred.thread != null) {
                Node next = node.next;
                if (next != null && next.waitStatus <= 0)
                    compareAndSetNext(pred, predNext, next);
            } else {
                unparkSuccessor(node);
            }

            node.next = node; // help GC
        }
    }

    /**
     * 方法名：应该Park，在获取锁失败之后，
     * 这个方法的作用就是，暂停当前线程，在当前线程获取锁失败之后。
     * Checks and updates status for a node that failed to acquire.
     * Returns true if thread should block. This is the main signal
     * control in all acquire loops.  Requires that pred == node.prev.
     *
     * @param pred node's predecessor holding status
     * @param node the node
     * @return {@code true} if thread should block
     */
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        //获取当前节点的前驱节点的【waitStatus】。
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            /*
             * 如果当前节点的前驱节点的状态为【SIGNAL】，直接返回。表示当前节点已经被【park阻塞了】。
             */
            return true;
        if (ws > 0) { //只有一种可能性会大于0，状态为取消。
            /*
             * 找到一个离【当前节点】，【最近的一个前驱节点（前驱节点的状态不能为CANCELLED）】。
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * waitStatus的状态必须为【0】、【PROPAGATE】（这里还有可能为CONDITION，不懂为什么排除了这种情况）。
             * 设置该状态为【SIGNAL】，但是缺不会【park】阻塞它，这和阻塞的方法，由后续的方法执行。
             */
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

    /**
     * 打断当前线程的便捷方法。
     */
    static void selfInterrupt() {
        Thread.currentThread().interrupt();
    }

    /**
     * 【park】阻塞当前线程，并且判断，这个线程是由【unpark】唤醒的，还是由【interrupt中断】唤醒的。
     * @return {@code true} if interrupted
     */
    private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        return Thread.interrupted();
    }

    /*
     * Various flavors of acquire, varying in exclusive/shared and
     * control modes.  Each is mostly the same, but annoyingly
     * different.  Only a little bit of factoring is possible due to
     * interactions of exception mechanics (including ensuring that we
     * cancel if tryAcquire throws exception) and other control, at
     * least not without hurting performance too much.
     */

    /**
     * Acquires in exclusive uninterruptible mode for thread already in
     * queue. Used by condition wait methods as well as acquire.
     *
     * @param node the node
     * @param arg the acquire argument
     * @return {@code true} if interrupted while waiting
     */
    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                        parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

    /**
     * Acquires in exclusive interruptible mode.
     * 【独占模式】下的【带有【中断效果】的获取锁】。
     */
    private void doAcquireInterruptibly(int arg)
            throws InterruptedException {
        //为当前线程创建一个【独占模式】的锁，并且入CLH队列，之后返回这个【node节点】信息。
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            //死循环。
            for (;;) {
                //获取当前节点的【前驱节点】。
                final Node p = node.predecessor();
                //如果【前驱节点】是【头节点（这意味着，当前节点，是第一个可以获取锁的节点了）】。就调用【tryAcquire】方法，尝试获取锁。
                if (p == head && tryAcquire(arg)) {
                    //如果获取到这个锁了。
                    //将当前节点设置为【头节点】。并重置一些参数，方便GC。
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return;
                }
                //将它的【前驱节点】，更新为【SIGNAL状态】，也就是【我，node】节点，要被【park】阻塞了，这样需要它（node节点）的前驱节点【也就是p】
                //后续将【node】唤醒。【SIGNAL：状态的描述就是，当前节点为SIGNAL，就意味着，我需要将后继节点唤醒一个】。
                if (shouldParkAfterFailedAcquire(p, node) &&
                        parkAndCheckInterrupt())            //阻塞当前线程，使用【park】方法。
                    throw new InterruptedException();       //判断，如果当前线程是由【中断唤醒的】，则抛出异常，如果是由【前驱节点的unpark方法唤醒的，则不需要抛出异常】。
            }
        } finally {
            //如果获取锁失败了，【也就是当前线程被【中断】异常唤醒了】，就需要取消当前【node节点】的等待锁状态，将它【waitStatus更新为：CANCELLED】。
            if (failed)
                cancelAcquire(node);
        }
    }

    /**
     * Acquires in exclusive timed mode.
     *
     * @param arg the acquire argument
     * @param nanosTimeout max wait time
     * @return {@code true} if acquired
     */
    private boolean doAcquireNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (nanosTimeout <= 0L)
            return false;
        final long deadline = System.nanoTime() + nanosTimeout;
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return true;
                }
                nanosTimeout = deadline - System.nanoTime();
                if (nanosTimeout <= 0L)
                    return false;
                if (shouldParkAfterFailedAcquire(p, node) &&
                        nanosTimeout > spinForTimeoutThreshold)
                    LockSupport.parkNanos(this, nanosTimeout);
                if (Thread.interrupted())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

    /**
     * Acquires in shared uninterruptible mode.
     * @param arg the acquire argument
     */
    private void doAcquireShared(int arg) {
        //向AQS同步队列，添加一个共享模式的节点。
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        if (interrupted)
                            selfInterrupt();
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                        parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

    /**
     * Acquires in shared interruptible mode.
     * @param arg the acquire argument
     */
    private void doAcquireSharedInterruptibly(int arg)
            throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                        parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

    /**
     * Acquires in shared timed mode.
     *
     * @param arg the acquire argument
     * @param nanosTimeout max wait time
     * @return {@code true} if acquired
     */
    private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (nanosTimeout <= 0L)
            return false;
        final long deadline = System.nanoTime() + nanosTimeout;
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return true;
                    }
                }
                nanosTimeout = deadline - System.nanoTime();
                if (nanosTimeout <= 0L)
                    return false;
                if (shouldParkAfterFailedAcquire(p, node) &&
                        nanosTimeout > spinForTimeoutThreshold)
                    LockSupport.parkNanos(this, nanosTimeout);
                if (Thread.interrupted())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

    // Main exported methods

    /**
     * Attempts to acquire in exclusive mode. This method should query
     * if the state of the object permits it to be acquired in the
     * exclusive mode, and if so to acquire it.
     *
     * <p>This method is always invoked by the thread performing
     * acquire.  If this method reports failure, the acquire method
     * may queue the thread, if it is not already queued, until it is
     * signalled by a release from some other thread. This can be used
     * to implement method {@link Lock#tryLock()}.
     *
     * <p>The default
     * implementation throws {@link UnsupportedOperationException}.
     *
     * @param arg the acquire argument. This value is always the one
     *        passed to an acquire method, or is the value saved on entry
     *        to a condition wait.  The value is otherwise uninterpreted
     *        and can represent anything you like.
     * @return {@code true} if successful. Upon success, this object has
     *         been acquired.
     * @throws IllegalMonitorStateException if acquiring would place this
     *         synchronizer in an illegal state. This exception must be
     *         thrown in a consistent fashion for synchronization to work
     *         correctly.
     * @throws UnsupportedOperationException if exclusive mode is not supported
     */
    protected boolean tryAcquire(int arg) {
        throw new UnsupportedOperationException();
    }

    /**
     * Attempts to set the state to reflect a release in exclusive
     * mode.
     *
     * <p>This method is always invoked by the thread performing release.
     *
     * <p>The default implementation throws
     * {@link UnsupportedOperationException}.
     *
     * @param arg the release argument. This value is always the one
     *        passed to a release method, or the current state value upon
     *        entry to a condition wait.  The value is otherwise
     *        uninterpreted and can represent anything you like.
     * @return {@code true} if this object is now in a fully released
     *         state, so that any waiting threads may attempt to acquire;
     *         and {@code false} otherwise.
     * @throws IllegalMonitorStateException if releasing would place this
     *         synchronizer in an illegal state. This exception must be
     *         thrown in a consistent fashion for synchronization to work
     *         correctly.
     * @throws UnsupportedOperationException if exclusive mode is not supported
     */
    protected boolean tryRelease(int arg) {
        throw new UnsupportedOperationException();
    }

    /**
     * Attempts to acquire in shared mode. This method should query if
     * the state of the object permits it to be acquired in the shared
     * mode, and if so to acquire it.
     *
     * <p>This method is always invoked by the thread performing
     * acquire.  If this method reports failure, the acquire method
     * may queue the thread, if it is not already queued, until it is
     * signalled by a release from some other thread.
     *
     * <p>The default implementation throws {@link
     * UnsupportedOperationException}.
     *
     * @param arg the acquire argument. This value is always the one
     *        passed to an acquire method, or is the value saved on entry
     *        to a condition wait.  The value is otherwise uninterpreted
     *        and can represent anything you like.
     * @return a negative value on failure; zero if acquisition in shared
     *         mode succeeded but no subsequent shared-mode acquire can
     *         succeed; and a positive value if acquisition in shared
     *         mode succeeded and subsequent shared-mode acquires might
     *         also succeed, in which case a subsequent waiting thread
     *         must check availability. (Support for three different
     *         return values enables this method to be used in contexts
     *         where acquires only sometimes act exclusively.)  Upon
     *         success, this object has been acquired.
     * @throws IllegalMonitorStateException if acquiring would place this
     *         synchronizer in an illegal state. This exception must be
     *         thrown in a consistent fashion for synchronization to work
     *         correctly.
     * @throws UnsupportedOperationException if shared mode is not supported
     */
    protected int tryAcquireShared(int arg) {
        throw new UnsupportedOperationException();
    }

    /**
     * Attempts to set the state to reflect a release in shared mode.
     *
     * <p>This method is always invoked by the thread performing release.
     *
     * <p>The default implementation throws
     * {@link UnsupportedOperationException}.
     *
     * @param arg the release argument. This value is always the one
     *        passed to a release method, or the current state value upon
     *        entry to a condition wait.  The value is otherwise
     *        uninterpreted and can represent anything you like.
     * @return {@code true} if this release of shared mode may permit a
     *         waiting acquire (shared or exclusive) to succeed; and
     *         {@code false} otherwise
     * @throws IllegalMonitorStateException if releasing would place this
     *         synchronizer in an illegal state. This exception must be
     *         thrown in a consistent fashion for synchronization to work
     *         correctly.
     * @throws UnsupportedOperationException if shared mode is not supported
     */
    protected boolean tryReleaseShared(int arg) {
        throw new UnsupportedOperationException();
    }

    /**
     * Returns {@code true} if synchronization is held exclusively with
     * respect to the current (calling) thread.  This method is invoked
     * upon each call to a non-waiting {@link ConditionObject} method.
     * (Waiting methods instead invoke {@link #release}.)
     *
     * <p>The default implementation throws {@link
     * UnsupportedOperationException}. This method is invoked
     * internally only within {@link ConditionObject} methods, so need
     * not be defined if conditions are not used.
     *
     * @return {@code true} if synchronization is held exclusively;
     *         {@code false} otherwise
     * @throws UnsupportedOperationException if conditions are not supported
     */
    protected boolean isHeldExclusively() {
        throw new UnsupportedOperationException();
    }

    /**
     * Acquires in exclusive mode, ignoring interrupts.  Implemented
     * by invoking at least once {@link #tryAcquire},
     * returning on success.  Otherwise the thread is queued, possibly
     * repeatedly blocking and unblocking, invoking {@link
     * #tryAcquire} until success.  This method can be used
     * to implement method {@link Lock#lock}.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquire} but is otherwise uninterpreted and
     *        can represent anything you like.
     */
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
                acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

    /**
     * Acquires in exclusive mode, aborting if interrupted.
     * Implemented by first checking interrupt status, then invoking
     * at least once {@link #tryAcquire}, returning on
     * success.  Otherwise the thread is queued, possibly repeatedly
     * blocking and unblocking, invoking {@link #tryAcquire}
     * until success or the thread is interrupted.  This method can be
     * used to implement method {@link Lock#lockInterruptibly}.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquire} but is otherwise uninterpreted and
     *        can represent anything you like.
     * @throws InterruptedException if the current thread is interrupted
     */
    public final void acquireInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (!tryAcquire(arg))
            doAcquireInterruptibly(arg);
    }

    /**
     * Attempts to acquire in exclusive mode, aborting if interrupted,
     * and failing if the given timeout elapses.  Implemented by first
     * checking interrupt status, then invoking at least once {@link
     * #tryAcquire}, returning on success.  Otherwise, the thread is
     * queued, possibly repeatedly blocking and unblocking, invoking
     * {@link #tryAcquire} until success or the thread is interrupted
     * or the timeout elapses.  This method can be used to implement
     * method {@link Lock#tryLock(long, TimeUnit)}.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquire} but is otherwise uninterpreted and
     *        can represent anything you like.
     * @param nanosTimeout the maximum number of nanoseconds to wait
     * @return {@code true} if acquired; {@code false} if timed out
     * @throws InterruptedException if the current thread is interrupted
     */
    public final boolean tryAcquireNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        return tryAcquire(arg) ||
                doAcquireNanos(arg, nanosTimeout);
    }

    /**
     * Releases in exclusive mode.  Implemented by unblocking one or
     * more threads if {@link #tryRelease} returns true.
     * This method can be used to implement method {@link Lock#unlock}.
     *
     * @param arg the release argument.  This value is conveyed to
     *        {@link #tryRelease} but is otherwise uninterpreted and
     *        can represent anything you like.
     * @return the value returned from {@link #tryRelease}
     */
    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

    /**
     * Acquires in shared mode, ignoring interrupts.  Implemented by
     * first invoking at least once {@link #tryAcquireShared},
     * returning on success.  Otherwise the thread is queued, possibly
     * repeatedly blocking and unblocking, invoking {@link
     * #tryAcquireShared} until success.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquireShared} but is otherwise uninterpreted
     *        and can represent anything you like.
     */
    public final void acquireShared(int arg) {
        if (tryAcquireShared(arg) < 0)
            doAcquireShared(arg);
    }

    /**
     * Acquires in shared mode, aborting if interrupted.  Implemented
     * by first checking interrupt status, then invoking at least once
     * {@link #tryAcquireShared}, returning on success.  Otherwise the
     * thread is queued, possibly repeatedly blocking and unblocking,
     * invoking {@link #tryAcquireShared} until success or the thread
     * is interrupted.
     * @param arg the acquire argument.
     * This value is conveyed to {@link #tryAcquireShared} but is
     * otherwise uninterpreted and can represent anything
     * you like.
     * @throws InterruptedException if the current thread is interrupted
     */
    public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }

    /**
     * Attempts to acquire in shared mode, aborting if interrupted, and
     * failing if the given timeout elapses.  Implemented by first
     * checking interrupt status, then invoking at least once {@link
     * #tryAcquireShared}, returning on success.  Otherwise, the
     * thread is queued, possibly repeatedly blocking and unblocking,
     * invoking {@link #tryAcquireShared} until success or the thread
     * is interrupted or the timeout elapses.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquireShared} but is otherwise uninterpreted
     *        and can represent anything you like.
     * @param nanosTimeout the maximum number of nanoseconds to wait
     * @return {@code true} if acquired; {@code false} if timed out
     * @throws InterruptedException if the current thread is interrupted
     */
    public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        return tryAcquireShared(arg) >= 0 ||
                doAcquireSharedNanos(arg, nanosTimeout);
    }

    /**
     * Releases in shared mode.  Implemented by unblocking one or more
     * threads if {@link #tryReleaseShared} returns true.
     *
     * @param arg the release argument.  This value is conveyed to
     *        {@link #tryReleaseShared} but is otherwise uninterpreted
     *        and can represent anything you like.
     * @return the value returned from {@link #tryReleaseShared}
     */
    public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }

    // Queue inspection methods

    /**
     * Queries whether any threads are waiting to acquire. Note that
     * because cancellations due to interrupts and timeouts may occur
     * at any time, a {@code true} return does not guarantee that any
     * other thread will ever acquire.
     *
     * <p>In this implementation, this operation returns in
     * constant time.
     *
     * @return {@code true} if there may be other threads waiting to acquire
     */
    public final boolean hasQueuedThreads() {
        return head != tail;
    }

    /**
     * Queries whether any threads have ever contended to acquire this
     * synchronizer; that is if an acquire method has ever blocked.
     *
     * <p>In this implementation, this operation returns in
     * constant time.
     *
     * @return {@code true} if there has ever been contention
     */
    public final boolean hasContended() {
        return head != null;
    }

    /**
     * Returns the first (longest-waiting) thread in the queue, or
     * {@code null} if no threads are currently queued.
     *
     * <p>In this implementation, this operation normally returns in
     * constant time, but may iterate upon contention if other threads are
     * concurrently modifying the queue.
     *
     * @return the first (longest-waiting) thread in the queue, or
     *         {@code null} if no threads are currently queued
     */
    public final Thread getFirstQueuedThread() {
        // handle only fast path, else relay
        return (head == tail) ? null : fullGetFirstQueuedThread();
    }

    /**
     * Version of getFirstQueuedThread called when fastpath fails
     */
    private Thread fullGetFirstQueuedThread() {
        /*
         * The first node is normally head.next. Try to get its
         * thread field, ensuring consistent reads: If thread
         * field is nulled out or s.prev is no longer head, then
         * some other thread(s) concurrently performed setHead in
         * between some of our reads. We try this twice before
         * resorting to traversal.
         */
        Node h, s;
        Thread st;
        if (((h = head) != null && (s = h.next) != null &&
                s.prev == head && (st = s.thread) != null) ||
                ((h = head) != null && (s = h.next) != null &&
                        s.prev == head && (st = s.thread) != null))
            return st;

        /*
         * Head's next field might not have been set yet, or may have
         * been unset after setHead. So we must check to see if tail
         * is actually first node. If not, we continue on, safely
         * traversing from tail back to head to find first,
         * guaranteeing termination.
         */

        Node t = tail;
        Thread firstThread = null;
        while (t != null && t != head) {
            Thread tt = t.thread;
            if (tt != null)
                firstThread = tt;
            t = t.prev;
        }
        return firstThread;
    }

    /**
     * Returns true if the given thread is currently queued.
     *
     * <p>This implementation traverses the queue to determine
     * presence of the given thread.
     *
     * @param thread the thread
     * @return {@code true} if the given thread is on the queue
     * @throws NullPointerException if the thread is null
     */
    public final boolean isQueued(Thread thread) {
        if (thread == null)
            throw new NullPointerException();
        for (Node p = tail; p != null; p = p.prev)
            if (p.thread == thread)
                return true;
        return false;
    }

    /**
     * Returns {@code true} if the apparent first queued thread, if one
     * exists, is waiting in exclusive mode.  If this method returns
     * {@code true}, and the current thread is attempting to acquire in
     * shared mode (that is, this method is invoked from {@link
     * #tryAcquireShared}) then it is guaranteed that the current thread
     * is not the first queued thread.  Used only as a heuristic in
     * ReentrantReadWriteLock.
     */
    final boolean apparentlyFirstQueuedIsExclusive() {
        Node h, s;
        return (h = head) != null &&
                (s = h.next)  != null &&
                !s.isShared()         &&
                s.thread != null;
    }

    /**
     * Queries whether any threads have been waiting to acquire longer
     * than the current thread.
     *
     * <p>An invocation of this method is equivalent to (but may be
     * more efficient than):
     *  <pre> {@code
     * getFirstQueuedThread() != Thread.currentThread() &&
     * hasQueuedThreads()}</pre>
     *
     * <p>Note that because cancellations due to interrupts and
     * timeouts may occur at any time, a {@code true} return does not
     * guarantee that some other thread will acquire before the current
     * thread.  Likewise, it is possible for another thread to win a
     * race to enqueue after this method has returned {@code false},
     * due to the queue being empty.
     *
     * <p>This method is designed to be used by a fair synchronizer to
     * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>.
     * Such a synchronizer's {@link #tryAcquire} method should return
     * {@code false}, and its {@link #tryAcquireShared} method should
     * return a negative value, if this method returns {@code true}
     * (unless this is a reentrant acquire).  For example, the {@code
     * tryAcquire} method for a fair, reentrant, exclusive mode
     * synchronizer might look like this:
     *
     *  <pre> {@code
     * protected boolean tryAcquire(int arg) {
     *   if (isHeldExclusively()) {
     *     // A reentrant acquire; increment hold count
     *     return true;
     *   } else if (hasQueuedPredecessors()) {
     *     return false;
     *   } else {
     *     // try to acquire normally
     *   }
     * }}</pre>
     *
     * @return {@code true} if there is a queued thread preceding the
     *         current thread, and {@code false} if the current thread
     *         is at the head of the queue or the queue is empty
     * @since 1.7
     */
    public final boolean hasQueuedPredecessors() {
        // The correctness of this depends on head being initialized
        // before tail and on head.next being accurate if the current
        // thread is first in queue.
        Node t = tail; // Read fields in reverse initialization order
        Node h = head;
        Node s;
        return h != t &&
                ((s = h.next) == null || s.thread != Thread.currentThread());
    }


    // Instrumentation and monitoring methods

    /**
     * Returns an estimate of the number of threads waiting to
     * acquire.  The value is only an estimate because the number of
     * threads may change dynamically while this method traverses
     * internal data structures.  This method is designed for use in
     * monitoring system state, not for synchronization
     * control.
     *
     * @return the estimated number of threads waiting to acquire
     */
    public final int getQueueLength() {
        int n = 0;
        for (Node p = tail; p != null; p = p.prev) {
            if (p.thread != null)
                ++n;
        }
        return n;
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire.  Because the actual set of threads may change
     * dynamically while constructing this result, the returned
     * collection is only a best-effort estimate.  The elements of the
     * returned collection are in no particular order.  This method is
     * designed to facilitate construction of subclasses that provide
     * more extensive monitoring facilities.
     *
     * @return the collection of threads
     */
    public final Collection<Thread> getQueuedThreads() {
        ArrayList<Thread> list = new ArrayList<Thread>();
        for (Node p = tail; p != null; p = p.prev) {
            Thread t = p.thread;
            if (t != null)
                list.add(t);
        }
        return list;
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire in exclusive mode. This has the same properties
     * as {@link #getQueuedThreads} except that it only returns
     * those threads waiting due to an exclusive acquire.
     *
     * @return the collection of threads
     */
    public final Collection<Thread> getExclusiveQueuedThreads() {
        ArrayList<Thread> list = new ArrayList<Thread>();
        for (Node p = tail; p != null; p = p.prev) {
            if (!p.isShared()) {
                Thread t = p.thread;
                if (t != null)
                    list.add(t);
            }
        }
        return list;
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire in shared mode. This has the same properties
     * as {@link #getQueuedThreads} except that it only returns
     * those threads waiting due to a shared acquire.
     *
     * @return the collection of threads
     */
    public final Collection<Thread> getSharedQueuedThreads() {
        ArrayList<Thread> list = new ArrayList<Thread>();
        for (Node p = tail; p != null; p = p.prev) {
            if (p.isShared()) {
                Thread t = p.thread;
                if (t != null)
                    list.add(t);
            }
        }
        return list;
    }

    /**
     * Returns a string identifying this synchronizer, as well as its state.
     * The state, in brackets, includes the String {@code "State ="}
     * followed by the current value of {@link #getState}, and either
     * {@code "nonempty"} or {@code "empty"} depending on whether the
     * queue is empty.
     *
     * @return a string identifying this synchronizer, as well as its state
     */
    public String toString() {
        int s = getState();
        String q  = hasQueuedThreads() ? "non" : "";
        return super.toString() +
                "[State = " + s + ", " + q + "empty queue]";
    }


    // Internal support methods for Conditions

    /**
     * Returns true if a node, always one that was initially placed on
     * a condition queue, is now waiting to reacquire on sync queue.
     * @param node the node
     * @return true if is reacquiring
     */
    final boolean isOnSyncQueue(Node node) {
        if (node.waitStatus == Node.CONDITION || node.prev == null)
            return false;
        if (node.next != null) // If has successor, it must be on queue
            return true;
        /*
         * node.prev can be non-null, but not yet on queue because
         * the CAS to place it on queue can fail. So we have to
         * traverse from tail to make sure it actually made it.  It
         * will always be near the tail in calls to this method, and
         * unless the CAS failed (which is unlikely), it will be
         * there, so we hardly ever traverse much.
         */
        return findNodeFromTail(node);
    }

    /**
     * Returns true if node is on sync queue by searching backwards from tail.
     * Called only when needed by isOnSyncQueue.
     * @return true if present
     */
    private boolean findNodeFromTail(Node node) {
        Node t = tail;
        for (;;) {
            if (t == node)
                return true;
            if (t == null)
                return false;
            t = t.prev;
        }
    }

    /**
     * 转移所有的节点，从【Condition】类中，到【AQS】类中。
     * @param node the node
     * @return true if successfully transferred (else the node was
     * cancelled before signal)
     */
    final boolean transferForSignal(Node node) {
        /*
         * 修改节点的状态，从【CONDITION】变成普通的节点。
         * 如果失败了，那么意味着这个节点被取消了【CANCELLED】。
         */
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;

        /*
         * Splice onto queue and try to set waitStatus of predecessor to
         * indicate that thread is (probably) waiting. If cancelled or
         * attempt to set waitStatus fails, wake up to resync (in which
         * case the waitStatus can be transiently and harmlessly wrong).
         */
        //入【AQS的CLH】队列。
        Node p = enq(node);
        int ws = p.waitStatus;
        //如果这个节点，被取消了，或者设置【SIGNAL】失败了，则放行当前线程。
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            LockSupport.unpark(node.thread);
        return true;
    }

    /**
     * Transfers node, if necessary, to sync queue after a cancelled wait.
     * Returns true if thread was cancelled before being signalled.
     *
     * @param node the node
     * @return true if cancelled before the node was signalled
     * 转移node节点，在取消阻塞之后。
     */
    final boolean transferAfterCancelledWait(Node node) {
        //1：先修改当前节点的状态【CONDITION】为0，
        if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
            //进入【AQS】的队列中。
            enq(node);
            return true;
        }
        /*
         * 这一步是：如果当前线程入【CLH】队列失败，则{@link #signal}方法，已经唤醒了别的线程了，这个节点就不做任何处理，
         * 并且执行【yield】线程让步。这个节点，只能等下一次【signal】方法的调用了。
         */
        while (!isOnSyncQueue(node))
            Thread.yield();
        return false;
    }

    /**
     * Invokes release with current state value; returns saved state.
     * Cancels node and throws exception on failure.
     * @param node the condition node for this wait
     * @return previous sync state
     */
    final int fullyRelease(Node node) {
        boolean failed = true;
        try {
            int savedState = getState();
            if (release(savedState)) {
                failed = false;
                return savedState;
            } else {
                throw new IllegalMonitorStateException();
            }
        } finally {
            if (failed)
                node.waitStatus = Node.CANCELLED;
        }
    }

    // 与 conditions 相关的方法。

    /**
     * Queries whether the given ConditionObject
     * uses this synchronizer as its lock.
     * 判断当前Condition，是不是由这个同步器创建的。
     * @param condition the condition
     * @return {@code true} if owned
     * @throws NullPointerException if the condition is null
     */
    public final boolean owns(ConditionObject condition) {
        return condition.isOwnedBy(this);
    }

    /**
     * Queries whether any threads are waiting on the given condition
     * associated with this synchronizer. Note that because timeouts
     * and interrupts may occur at any time, a {@code true} return
     * does not guarantee that a future {@code signal} will awaken
     * any threads.  This method is designed primarily for use in
     * monitoring of the system state.
     * 判断当前条件变量中是否由等待的线程。
     * @param condition the condition
     * @return {@code true} if there are any waiting threads
     * @throws IllegalMonitorStateException if exclusive synchronization
     *         is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this synchronizer
     * @throws NullPointerException if the condition is null
     */
    public final boolean hasWaiters(ConditionObject condition) {
        if (!owns(condition))
            throw new IllegalArgumentException("Not owner");
        return condition.hasWaiters();
    }

    /**
     * Returns an estimate of the number of threads waiting on the
     * given condition associated with this synchronizer. Note that
     * because timeouts and interrupts may occur at any time, the
     * estimate serves only as an upper bound on the actual number of
     * waiters.  This method is designed for use in monitoring of the
     * system state, not for synchronization control.
     * 获取Condition的阻塞队列长度。
     * @param condition the condition
     * @return the estimated number of waiting threads
     * @throws IllegalMonitorStateException if exclusive synchronization
     *         is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this synchronizer
     * @throws NullPointerException if the condition is null
     */
    public final int getWaitQueueLength(ConditionObject condition) {
        if (!owns(condition))
            throw new IllegalArgumentException("Not owner");
        return condition.getWaitQueueLength();
    }

    /**
     * Returns a collection containing those threads that may be
     * waiting on the given condition associated with this
     * synchronizer.  Because the actual set of threads may change
     * dynamically while constructing this result, the returned
     * collection is only a best-effort estimate. The elements of the
     * returned collection are in no particular order.
     * 返回当前【条件变量Condition】中，阻塞的线程集合。需要是自己创建的【Condition】才行。
     * @param condition the condition
     * @return the collection of threads
     * @throws IllegalMonitorStateException if exclusive synchronization
     *         is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this synchronizer
     * @throws NullPointerException if the condition is null
     */
    public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
        if (!owns(condition))  // 判断当前Condition，是不是由这个同步器创建的。
            throw new IllegalArgumentException("Not owner");
        return condition.getWaitingThreads();
    }

    /**
     * Condition implementation for a {@link
     * AbstractQueuedSynchronizer} serving as the basis of a {@link
     * Lock} implementation.
     *
     * <p>Method documentation for this class describes mechanics,
     * not behavioral specifications from the point of view of Lock
     * and Condition users. Exported versions of this class will in
     * general need to be accompanied by documentation describing
     * condition semantics that rely on those of the associated
     * {@code AbstractQueuedSynchronizer}.
     *
     * <p>This class is Serializable, but all fields are transient,
     * so deserialized conditions have no waiters.
     * AQS的一个条件变量类，它可以用来阻塞某个线程。作用类似于【synchronized】的【wait/notify】
     */
    public class ConditionObject implements Condition, java.io.Serializable {
        private static final long serialVersionUID = 1173984872572414699L;
        /** Condition 的条件变量的阻塞队列的第一个元素  */
        private transient Node firstWaiter;
        /** Condition 条件变量的阻塞队列的最后一个元素 . */
        private transient Node lastWaiter;

        /**
         * Creates a new {@code ConditionObject} instance.
         */
        public ConditionObject() { }

        // 内部方法

        /**
         * 在Condition条件变量中，添加一个阻塞的线程节点。
         * @return its new wait node
         */
        private Node addConditionWaiter() {
            Node t = lastWaiter;
            // 如果最尾部的节点，自己取消了等待，则将其清除掉。
            if (t != null && t.waitStatus != Node.CONDITION) {
                unlinkCancelledWaiters();
                t = lastWaiter;
            }
            //将当前线程，封装成，CONDITION阻塞的样子，并进入阻塞队列。
            Node node = new Node(Thread.currentThread(), Node.CONDITION);
            if (t == null)
                firstWaiter = node;
            else
                t.nextWaiter = node;
            lastWaiter = node;
            return node;
        }

        /**
         * 放行一个饥饿点的线程，从第一个节点开始，放行第一个可以放行的线程.
         * @param first (non-null) the first node on condition queue
         */
        private void doSignal(Node first) {
            do {
                if ( (firstWaiter = first.nextWaiter) == null)
                    lastWaiter = null;
                first.nextWaiter = null;
            } while (!transferForSignal(first) &&
                    (first = firstWaiter) != null);
        }

        /**
         * Removes and transfers all nodes.
         * 移除，并转移所有的节点。
         * @param first (non-null) the first node on condition queue
         */
        private void doSignalAll(Node first) {
            lastWaiter = firstWaiter = null;
            do {
                Node next = first.nextWaiter;
                first.nextWaiter = null;
                transferForSignal(first);
                first = next;
            } while (first != null);
        }

        /**
         * Unlinks cancelled waiter nodes from condition queue.
         * Called only while holding lock. This is called when
         * cancellation occurred during condition wait, and upon
         * insertion of a new waiter when lastWaiter is seen to have
         * been cancelled. This method is needed to avoid garbage
         * retention in the absence of signals. So even though it may
         * require a full traversal, it comes into play only when
         * timeouts or cancellations occur in the absence of
         * signals. It traverses all nodes rather than stopping at a
         * particular target to unlink all pointers to garbage nodes
         * without requiring many re-traversals during cancellation
         * storms.
         * 取消等待，在【Condition的阻塞队列中】。
         */
        private void unlinkCancelledWaiters() {
            Node t = firstWaiter;
            Node trail = null;
            while (t != null) {
                Node next = t.nextWaiter;
                if (t.waitStatus != Node.CONDITION) {
                    t.nextWaiter = null;
                    if (trail == null)
                        firstWaiter = next;
                    else
                        trail.nextWaiter = next;
                    if (next == null)
                        lastWaiter = trail;
                }
                else
                    trail = t;
                t = next;
            }
        }

        // Condition的公共方法。

        /**
         * 激活一个等待时间最久的线程。也就是头节点的线程。
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
         *         returns {@code false}
         */
        public final void signal() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;
            if (first != null)
                doSignal(first); // 放行头节点的线程。
        }

        /**
         * 转移所有的【Condition】中的【阻塞队列】中的节点，到【AQS的CLH】队列中
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
         *         returns {@code false}
         */
        public final void signalAll() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;
            if (first != null)
                doSignalAll(first);
        }

        /**
         * Implements uninterruptible condition wait.
         * <ol>
         * <li> Save lock state returned by {@link #getState}.
         * <li> Invoke {@link #release} with saved state as argument,
         *      throwing IllegalMonitorStateException if it fails.
         * <li> Block until signalled.
         * <li> Reacquire by invoking specialized version of
         *      {@link #acquire} with saved state as argument.
         * </ol>
         * 这是一个【会忽略中断的阻塞】。具体做法就是：在出现中断的地方。
         *  直接重置中断状态。不管中断。
         */
        public final void awaitUninterruptibly() {
            Node node = addConditionWaiter();
            int savedState = fullyRelease(node);
            boolean interrupted = false;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if (Thread.interrupted())
                    interrupted = true;
            }
            if (acquireQueued(node, savedState) || interrupted) // 不对中断，做任何的处理，之前出现了中断，这里就重置一下中断状态。
                selfInterrupt();
        }

        /*
         * For interruptible waits, we need to track whether to throw
         * InterruptedException, if interrupted while blocked on
         * condition, versus reinterrupt current thread, if
         * interrupted while blocked waiting to re-acquire.
         * 对于【可以中断的阻塞】，我们需要去判断，处理行为为：【抛出中断异常】、【还是重新调用park方法，打断自己】。
         * 判断条件就是：当前node，是否发生了转移。从【Condition】阻塞队列，转移到【AQS的CLH队列】。
         */

        /** 意味着，对于Condition状态下的节点，可以重新调用【park】方法，进入阻塞，来解决中断。 */
        private static final int REINTERRUPT =  1;
        /** 意味着，对于Condition状态下的节点，需要抛出异常，解决中断。 */
        private static final int THROW_IE    = -1;

        /**
         * Checks for interrupt, returning THROW_IE if interrupted
         * before signalled, REINTERRUPT if after signalled, or
         * 0 if not interrupted.
         * 这个是在阻塞的时候，检查一下，是否出现了中断：
         * 返回 0： 没有出现中断。
         * 返回 -1：出现了中断，并且【这个node节点，从Condition的阻塞队列】已经【转移到了AQS的CLH】队列。
         *      只能抛出异常处理了。
         * 返回 1：表示出现了中断，但是【这个node节点，还没有从Condition阻塞队列】转移到【AQS的CLH】队列。
         *      这个时候，可以根据情况，执行【抛出异常处理】、【重新中断】。
         */
        private int checkInterruptWhileWaiting(Node node) {
            return Thread.interrupted() ?
                    (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
                    0;
        }

        /**
         * 处理中断唤醒的线程。
         * 有两种处理方式：要么抛异常，要么重新中断。
         */
        private void reportInterruptAfterWait(int interruptMode)
                throws InterruptedException {
            if (interruptMode == THROW_IE)
                throw new InterruptedException();
            else if (interruptMode == REINTERRUPT)
                selfInterrupt();
        }

        /**
         * Implements interruptible condition wait.
         * <ol>
         * <li> If current thread is interrupted, throw InterruptedException.
         * <li> Save lock state returned by {@link #getState}.
         * <li> Invoke {@link #release} with saved state as argument,
         *      throwing IllegalMonitorStateException if it fails.
         * <li> Block until signalled or interrupted.
         * <li> Reacquire by invoking specialized version of
         *      {@link #acquire} with saved state as argument.
         * <li> If interrupted while blocked in step 4, throw InterruptedException.
         * </ol>
         * 所有的await方法都类似。大致步骤如下：
         *  1：判断当前线程是否有中断，如果有【抛出中断异常】。
         *  2：如果没有，则将【当前节点】，添加到【Condition】的阻塞队列中。
         *  3：之后唤醒【AQS】的【CLH队列】中的后继节点。（这也就是为什么它必须获取到锁，才能执行这个方法的原因。）也就是【Condition必须要lock代码块中】。
         *  4：判断当前节点的状态是否为【CONDITION（就怕阻塞之前，他已经被唤醒了）】。如果是，则调用【park】方法，阻塞当前线程。
         *  5：下一步：唤醒，当出现【unpark】、【中断】、【超时】时，都可以唤醒当前线程。
         *      5.1：unpark正常唤醒，先将自己从【Condition】阻塞队列中，转移到【AQS】的【CLH队列】，之后再获取锁。
         *          如果没有成功。则调用【park】方法，再次阻塞自己。
         *      5.2：中断：抛出异常。
         *      5.3：超时，和unpark行为一样。
         */
        public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
        }

        /**
         * Implements timed condition wait.
         * <ol>
         * <li> If current thread is interrupted, throw InterruptedException.
         * <li> Save lock state returned by {@link #getState}.
         * <li> Invoke {@link #release} with saved state as argument,
         *      throwing IllegalMonitorStateException if it fails.
         * <li> Block until signalled, interrupted, or timed out.
         * <li> Reacquire by invoking specialized version of
         *      {@link #acquire} with saved state as argument.
         * <li> If interrupted while blocked in step 4, throw InterruptedException.
         * </ol>
         * 所有的await方法都类似。
         */
        public final long awaitNanos(long nanosTimeout)
                throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();
            int savedState = fullyRelease(node);
            final long deadline = System.nanoTime() + nanosTimeout;
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                if (nanosTimeout <= 0L) {
                    transferAfterCancelledWait(node);
                    break;
                }
                if (nanosTimeout >= spinForTimeoutThreshold)
                    LockSupport.parkNanos(this, nanosTimeout);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
                nanosTimeout = deadline - System.nanoTime();
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null)
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
            return deadline - System.nanoTime();
        }

        /**
         * Implements absolute timed condition wait.
         * <ol>
         * <li> If current thread is interrupted, throw InterruptedException.
         * <li> Save lock state returned by {@link #getState}.
         * <li> Invoke {@link #release} with saved state as argument,
         *      throwing IllegalMonitorStateException if it fails.
         * <li> Block until signalled, interrupted, or timed out.
         * <li> Reacquire by invoking specialized version of
         *      {@link #acquire} with saved state as argument.
         * <li> If interrupted while blocked in step 4, throw InterruptedException.
         * <li> If timed out while blocked in step 4, return false, else true.
         * </ol>
         * 这几个await方法都类似。
         */
        public final boolean awaitUntil(Date deadline)
                throws InterruptedException {
            long abstime = deadline.getTime();
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();
            int savedState = fullyRelease(node);
            boolean timedout = false;
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                if (System.currentTimeMillis() > abstime) {
                    timedout = transferAfterCancelledWait(node);
                    break;
                }
                LockSupport.parkUntil(this, abstime);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null)
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
            return !timedout;
        }

        /**
         * Condition中await方法的实现：实现细节如下：
         * <ol>
         * <li> 如果当前线程【被中断 interrupted】，抛出【InterruptedException】。
         * <li> 获取锁的状态 {@link #getState}.
         * <li> 调用 {@link #release} 方法，去释放当前锁资源。如果是失败了，则抛出 【IllegalMonitorStateException】
         * <li> 打破阻塞的条件有：【signalled】、【interrupted】、【timed out】。signal方法唤醒、interrupt中断、timeOut超时。
         * <li> 通过 {@link #acquire} 方法的返回值重新获取锁。
         *  <li> 如果被中断唤醒，则抛出【InterruptedException】。
         *  <li> 如果被超时唤醒， return false, else true.
         *  </ol>
         */
        public final boolean await(long time, TimeUnit unit)
                throws InterruptedException {
            //转换成统一单位：nanos。
            long nanosTimeout = unit.toNanos(time);
            //1：如果被中断了，则抛出中断异常。
            if (Thread.interrupted())
                throw new InterruptedException();
            //2：添加一个新的节点，到Node节点中。每一个【Condition，都维护了自己的一个阻塞队列】。
            Node node = addConditionWaiter();
            //3：释放当前资源锁，这个方法会唤醒当前节点的后继节点。
            int savedState = fullyRelease(node);
            final long deadline = System.nanoTime() + nanosTimeout;
            boolean timedout = false;
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                //判断阻塞时间。如果阻塞时间小于0，则不用阻塞，直接返回。
                if (nanosTimeout <= 0L) {
                    //将当前节点，从【Condition的阻塞队列中】移到【AQS中的CLH队列中】。
                    timedout = transferAfterCancelledWait(node);
                    break;
                }
                //如果当前阻塞时间，【大于自旋等待的时间】。则执行【park】方法阻塞线程。
                if (nanosTimeout >= spinForTimeoutThreshold)
                    LockSupport.parkNanos(this, nanosTimeout);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)//如果出现了【中断】，就需要跳出这个循环了。
                    break;
                nanosTimeout = deadline - System.nanoTime();
                //最后：如果当前【阻塞时间小于自旋等待时间】，则什么都不处理，等它一直执行这个循环。【叫做自旋】。
            }
            //重新获取锁，如果没有获取到锁，并且还被中断唤醒了，则将状态设置为：【重新中断】，在后续重新【park】。
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null)
                unlinkCancelledWaiters();
            if (interruptMode != 0)  //不等于 0，表示它是由【中断唤醒的】。
                reportInterruptAfterWait(interruptMode);
            return !timedout;
        }

        // 下面是一个与Condition相关的方法，可以看到，下面的这些方法，都要求【isHeldExclusively】
        // 也就是【只有当前线程持有这个锁】，才能对这个【锁，创建的Condition进行操作】。与【synchronized】一摸一样。
        //【notify/wait】等方法，也只能在【synchronized】中执行。

        /**
         * 判断当前这个Condition是不是由这个类创建的。
         *
         * @return {@code true} if owned
         */
        final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
            return sync == AbstractQueuedSynchronizer.this;
        }

        /**
         * 判断当前ConditionObject中是否还有阻塞的线程。
         * Implements {@link AbstractQueuedSynchronizer#hasWaiters(ConditionObject)}.
         *
         * @return {@code true} if there are any waiting threads
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
         *         returns {@code false}
         */
        protected final boolean hasWaiters() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
                if (w.waitStatus == Node.CONDITION)
                    return true;
            }
            return false;
        }

        /**
         * 返回当前ConditionObject中阻塞线程的长度。
         * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength(ConditionObject)}.
         *
         * @return the estimated number of waiting threads
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
         *         returns {@code false}
         */
        protected final int getWaitQueueLength() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            int n = 0;
            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
                if (w.waitStatus == Node.CONDITION)
                    ++n;
            }
            return n;
        }

        /**
         * 返回所有状态为【CONDITION】的线程。也就是被条件阻塞【条件为：内部类ConditionObject】的线程。
         * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads(ConditionObject)}.
         *
         * @return the collection of threads
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
         *         returns {@code false}
         */
        protected final Collection<Thread> getWaitingThreads() {
            //需要子类实现的方法，也就是判断【当前线程】是否持有这个【独占模式的锁】。
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            ArrayList<Thread> list = new ArrayList<Thread>();
            //依次，遍历所有的ConditionObject中阻塞的线程。
            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
                if (w.waitStatus == Node.CONDITION) {
                    Thread t = w.thread;
                    if (t != null)
                        list.add(t);
                }
            }
            return list;
        }
    }

    /**
     * 设置CAS的操作。
     */
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long stateOffset;
    private static final long headOffset;
    private static final long tailOffset;
    private static final long waitStatusOffset;
    private static final long nextOffset;

    static {
        try {
            stateOffset = unsafe.objectFieldOffset
                    (AbstractQueuedSynchronizer.class.getDeclaredField("state"));
            headOffset = unsafe.objectFieldOffset
                    (AbstractQueuedSynchronizer.class.getDeclaredField("head"));
            tailOffset = unsafe.objectFieldOffset
                    (AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
            waitStatusOffset = unsafe.objectFieldOffset
                    (Node.class.getDeclaredField("waitStatus"));
            nextOffset = unsafe.objectFieldOffset
                    (Node.class.getDeclaredField("next"));

        } catch (Exception ex) { throw new Error(ex); }
    }

    /**
     * CAS操作，在{@link #enq}中，初始化CLH队列时调用。
     */
    private final boolean compareAndSetHead(Node update) {
        return unsafe.compareAndSwapObject(this, headOffset, null, update);
    }

    /**
     * CAS操作，只有在{@link #enq}入队列的方法中调用。
     */
    private final boolean compareAndSetTail(Node expect, Node update) {
        return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
    }

    /**
     * CAS 操作，设置当前节点的 waitStatus。
     */
    private static final boolean compareAndSetWaitStatus(Node node,
                                                         int expect,
                                                         int update) {
        return unsafe.compareAndSwapInt(node, waitStatusOffset,
                expect, update);
    }

    /**
     * CAS next field of a node.
     * 使用CAS操作，设置下一个node。
     * 在{@link #cancelAcquire}方法中调用。
     * 也就是【当前节点取消获取锁的时候】，设置它的后继节点。
     */
    private static final boolean compareAndSetNext(Node node,
                                                   Node expect,
                                                   Node update) {
        return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
    }
}
